<template>
  <Dialog v-model="dialogVisible" title="发送模板消息目标用户">
    <el-form ref="formRef" v-loading="formLoading" :model="queryParams" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="13">
          <el-form-item label="用户标识" prop="url">
            <el-input
              v-model="queryParams.openid"
              @keyup.enter="handleQuery"
              placeholder="公众号用户的openId"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="用户昵称" prop="appid">
            <el-input
              v-model="queryParams.nickname"
              @keyup.enter="handleQuery"
              placeholder="公众号用户昵称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="11">
          <el-form-item label="用户省份" prop="appid">
            <el-input
              v-model="queryParams.province"
              @keyup.enter="handleQuery"
              placeholder="公众号用户所属省份"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户城市" prop="appid">
            <el-input
              v-model="queryParams.city"
              @keyup.enter="handleQuery"
              placeholder="公众号用户所属城市"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="13">
          <el-form-item label="用户标签">
            <el-select
              v-model="queryParams.tagId"
              filterable
              placeholder="选择用户分组"
              :loading="wxUsersLoading"
            >
              <el-option
                v-for="item in wxUserTags"
                :key="item.id"
                :label="item.name"
                :value="item.tagId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2" />
        <el-col :span="9">
          <el-button @click="handleQuery"> <Icon icon="ep:search" />筛选 </el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" /> 重置</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div class="user-list-send">
      <div class="user-title-message">消息预览：</div>
      <div class="template-area">
        <el-input
          type="textarea"
          disabled
          autosize
          v-model="templateContent"
          placeholder="模版加载中..."
        />
      </div>
      <div class="user-title-message mb5">本消息将发送给：</div>
      <div class="user-list" v-loading="wxUsersLoading">
        <div class="user-card" v-for="item in wxUserList" :key="item.openid">
          <el-avatar :src="item.headimgurl" />
          <div class="nickname">{{ item.nickname }}</div>
        </div>
        <span v-show="totalCount > 10">...</span>
        等共（ <span class="text-success">{{ totalCount }}</span> ）位用户
      </div>
    </div>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">发 送</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as MpTemplateApi from '@/api/mp/template'
import * as MpUserApi from '@/api/mp/user'
import * as MpTagApi from '@/api/mp/tag'

defineOptions({ name: 'MpUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const wxUsersLoading = ref(false) // 发送的用户
const wxUserList = ref([]) // 发送的用户组
const totalCount = ref() // 可发送的用户数量
const wxUserTags = ref([]) // 用户标签
const formRef = ref() // 表单 Ref
const templateContent = ref() // 模板内容

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  accountId: -1,
  openid: '',
  nickname: '',
  province: '',
  city: '',
  tagId: []
})
const templateId = ref()

/** 打开弹窗 */
const open = async (id: number, accountId: number) => {
  dialogVisible.value = true
  resetForm()
  try {
    wxUsersLoading.value = true
    queryParams.accountId = accountId
    templateId.value = id
    const userResponse = await MpUserApi.getUserPageEnhance(queryParams)
    wxUserTags.value = await MpTagApi.getSimpleTagList()
    totalCount.value = userResponse.total
    wxUserList.value = userResponse.list

    templateContent.value = await MpTemplateApi.getTemplateContent(id)
  } finally {
    wxUsersLoading.value = false
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 查询列表 */
const getList = async () => {
  try {
    wxUsersLoading.value = true
    const userData = await MpUserApi.getUserPageEnhance(queryParams)
    wxUserList.value = userData.list
    totalCount.value = userData.total
  } finally {
    wxUsersLoading.value = false
  }
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    let newQueryParams = { ...queryParams }
    newQueryParams.id = templateId.value
    await MpTemplateApi.sendMsgBatchTemplate(newQueryParams)
    message.success(t('common.success'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const resetQuery = () => {
  resetForm()
  getList()
}
/** 重置表单 */
const resetForm = () => {
  queryParams.pageNo = 1
  queryParams.pageSize = 10
  queryParams.openid = ''
  queryParams.nickname = ''
  queryParams.province = ''
  queryParams.city = ''
  queryParams.tagId = []
}
</script>
<style scoped>
.user-list-send {
  margin-top: 20px;
  border: 1px dotted gray;
  padding: 10px;
}
.user-title-message {
  font-size: 15px;
  font-weight: bold;
}
.template-area {
  margin: 20px 0;
}
.user-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.user-card {
  overflow: hidden;
  max-width: 60px;
  margin: 5px;
  text-align: center;
}
.nickname {
  color: #999999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
